<template>
    <el-popover
        placement="top-start"
        width="1200"
        trigger="manual"
        :visible-arrow="false"
        v-model="visible"
        @show="bindKeyDownEvent"
        @hide="unbindKeyDownEvent"
        popper-class="testClass"
    >
        <el-row  :gutter="20" style="margin-bottom:10px">
            <el-col :span="6">
                <el-input size="mini" :disabled="formObj.key === 'goodsCnName' ? true : false" placeholder="请输入商品名称"  v-model='searchForm.goodsCnName'/>
            </el-col>
            <el-col :span="6">
                <el-input size="mini" :disabled="formObj.key === 'goodsHsCode' ? true : false"  placeholder="请输入商品编码"  v-model='searchForm.goodsHsCode'/>
            </el-col>
            <el-col :span="6">
                <el-input size="mini" :disabled="formObj.key === 'goodsModel' ? true : false" placeholder="请输入规格型号"  v-model='searchForm.goodsModel'/>
            </el-col>
        </el-row>
        <el-table 
            :data="gridData" 
            height="420"  
            border 
            :id="`J-gridData${formObj.next}`" 
            empty-text="没有匹配数据"
            @row-click="rowCellClick"
            @row-dblclick="dealEnterCallback(formObj.next, $event)" 
            highlight-current-row
            ref="gridDataRef"
        >
        <el-table-column  align='center' label="操作"  min-width="60">
            <template slot-scope="scope">
                <el-button size="mini" @click="selectHistoryData(scope.row, 'part')" style="cursor:pointer;font-size:12px;padding:3px 4px;borderRadius:4px" round>部分选择</el-button>
            </template>
        </el-table-column>
        <el-table-column min-width="120" property="goodsCnName" label="商品名称">
          <template slot-scope="scope">
            <p v-html='scope.row.goodsCnName_show'></p>
          </template>
        </el-table-column>
        <el-table-column min-width="80" property="goodsHsCode" label="商品编码">
          <template slot-scope="scope">
            <p v-html='scope.row.goodsHsCode_show'></p>
          </template>
        </el-table-column>
        <el-table-column min-width="240" property="goodsModel" label="规格型号">
          <template slot-scope="scope">
            <p v-html='scope.row.goodsModel_show'></p>
          </template>
        </el-table-column>
        <el-table-column min-width="60" property="currencyName" label="币制"></el-table-column>
        <el-table-column min-width="70" property="destinationCountryName" label="最终目的国"></el-table-column>
        <el-table-column min-width="60" property="originCodeName" label="原产国"></el-table-column>
        <el-table-column min-width="80" property="destinationAreaName" label="境内货源地"></el-table-column>
        <el-table-column min-width="80" property="destinationDetailAreaName" label="货源地详细"></el-table-column>
        <el-table-column min-width="60" property="quantityUnitName" label="成交单位"></el-table-column>
        <el-table-column min-width="60" property="firstUnitName" label="法定单位"></el-table-column>
        <el-table-column min-width="60" property="secondUnitName" label="第二单位"></el-table-column>
        </el-table>
        <el-form-item size='mini' slot="reference">
            <el-input :ref="`${formObj.key}Ref`"  v-model='form[formObj.key]' @keyup.enter.native="dealEnterCallback(formObj.next, $event)"  >
              <template v-if="tool"  slot="append" ><i class="el-icon-search" @click="searchShopCode"></i></template>
            </el-input>
        </el-form-item>
    </el-popover>
</template>
<script>
export default {
  name: 'RemoteSelect',
  props: {
    formData: Object,
    formObj: Object,
    curOperType: String,
    tool: Boolean,
    isSetting: Boolean
  },
  data() {
    return {
      form: {},
      preform: {},
      curIndex: 0,
      searchForm: {},
      formLabelWidth: '120px',
      gridData: [],
      visible: false
    }
  },
  watch: {
    formData: {
      immediate: true,
      deep: true,
      handler(curform = {}) {
        const {
          key
        } = this.formObj
        const compareOption = ['goodsCnName', 'goodsHsCode', 'goodsModel']
        let count = 0
        //  判断是否是选择操作
        compareOption.map(item => {
          if (curform[item] !== this.preform[item]) {
            count++
          }
        })
        if (curform[key] !== this.preform[key]) {
          console.log('发生了' + key + '操作', count)
          this.searchForm[key] = curform[key]
          this.preform = JSON.parse(JSON.stringify(curform))
          if (count === 1) {
            this.searchData(true)
          }
        }
        this.form = curform
        this.curIndex = -1
      }
    },
    searchForm: {
      immediate: true,
      deep: true,
      handler() {
        this.curIndex = -1
        this.searchData()
      }
    },
    visible(cur) {
      const {
        key
      } = this.formObj
      if (cur && this.form[key]) {
        this.searchForm[key] = this.form[key]
      }
    }
  },
  mounted() {
    this.$emit('update:formData', this.form)
  },
  methods: {
    searchShopCode($event) {
      const type = this.formObj.key === 'goodsModel' ? 'showInfo' : 'isShow'
      this.$emit('searchShopCode', type, $event)
    },
    searchData(canHide, obj = {}) {
      if (this.isSetting) {
        return false
      }
      const searchArr = []
      Object.entries({ ...this.searchForm, ...obj }).map(item => {
        const [key, value] = item
        if (value) {
          if (key === 'goodsModel') {
            //  这里需要对规格型号进行特殊处理 并且得有值
            if (value && typeof value === 'string') {
              const subSearchKey = value.split('|')
              subSearchKey.map(item => {
                searchArr.push({
                  [key]: new RegExp(item)
                })
              })
            }
          } else {
            searchArr.push({
              [key]: new RegExp(value)
            })
          }
        }
      })
      //  光标消失的时候 不让他弹出选择 不能删除
      if (searchArr.length < 1) {
        return false
      }
      this.findCompanyDataByFilter({
        $and: searchArr
      }).then(res => {
        const {
          data
        } = res
        if (data.length < 1 && canHide) {
          this.closeWin()
        } else {
          this.visible = true
        }
        //  高亮查询数据
        this.gridData = data.map(item => {
          item.goodsCnName_show = this.getHighlightWord(item, 'goodsCnName')
          item.goodsHsCode_show = this.getHighlightWord(item, 'goodsHsCode')
          item.goodsModel_show = this.getHighlightWord(item, 'goodsModel')
          return item
        })
        this.curIndex = -1
      })
    },
    getHighlightWord(row, key) {
      const searh_val = this.searchForm[key]
      if (row[key]) {
        //  对于规格描述 做特殊处理
        if (key === 'goodsModel') {
          let deststr = row[key]
          if (searh_val && typeof searh_val === 'string') {
            searh_val.split('|').map(item => {
              if (item) {
                deststr = deststr.split(item).join('<span style="color:#56abe4">' + item + '</span>')
              }
            })
          }
          return deststr
        } else {
          return row[key].split(searh_val).join('<span style="color:#56abe4">' + searh_val + '</span>')
        }
      } else {
        return ''
      }
    },
    // 获取商品信息
    findCompanyDataByFilter(filterOb = {}, p = 1, pagesize = 10) {
      return new Promise((resolve) => {
        this.$db.companyData.find(filterOb).skip(p).limit(pagesize).sort({ code: 1 }).exec((err, docs) => {
          resolve({
            data: docs,
            err
          })
        })
      })
    },
    getFromData(row, type = 'part') {
      let obj = {
        goodsCnName: row.goodsCnName,
        goodsHsCode: row.goodsHsCode,
        goodsModel: row.goodsModel,
        quantityUnit: row.quantityUnit,
        quantityUnitName: row.quantityUnitName,
        secondUnit: row.secondUnit,
        secondUnitName: row.secondUnitName,
        firstUnit: row.firstUnit,
        firstUnitName: row.firstUnitName
      }
      if (type === 'all') {
        obj = {
          ...obj,
          dutyMode: row.dutyMode,
          dutyModeName: row.dutyModeName,
          currencyName: row.currencyName,
          currency: row.currency,
          originCode: row.originCode,
          destinationCountry: row.destinationCountry,
          destinationArea: row.destinationArea,
          destinationDetailArea: row.destinationDetailArea,
          originCodeName: row.originCodeName,
          destinationCountryName: row.destinationCountryName,
          destinationAreaName: row.destinationAreaName,
          destinationDetailAreaName: row.destinationDetailAreaName
        }
      }
      return obj
    },
    selectHistoryData(row, type) {
      const {
        key
      } = this.formObj
      this.$emit('combineSelect', this.getFromData(row, type))
      this.searchForm[key] = row[key]// TODO
      this.closeWin()
    },
    dealEnterCallback(type, $event) {
      const {
        key
      } = this.formObj
      this.$refs[key + 'Ref'].blur()
      if (this.curIndex !== -1 && this.gridData[this.curIndex]) {
        this.$emit('dealEnterCallback', 'quantity', $event)
        this.selectHistoryData(this.gridData[this.curIndex || 0], 'all')
      } else {
        this.$emit('dealEnterCallback', type, $event)
        this.closeWin()
      }
    },
    rowCellClick(row, col, $event) {
      this.curIndex = this.gridData.findIndex(item => item._id === row._id)
    },
    //  进入Popper 绑定 出来的时候解绑
    bindKeyDownEvent() {
      var that = this
      const {
        next,
        key
      } = this.formObj
      this.$emit('hideOtherWin', key)
      document.onkeydown = (e) => {
        e = e || event
        //  37 left 39 right
        if ([37, 38, 39, 40].includes(e.keyCode)) {
          if (e.keyCode === 38) {
            that.curIndex = that.curIndex < 1 ? 0 : that.curIndex - 1
          } else if (e.keyCode === 40) {
            that.curIndex = that.curIndex >= that.gridData.length - 2 ? that.gridData.length - 1 : that.curIndex + 1
          }
          //  表格元素
          const elements = document.querySelectorAll('#J-gridData' + next + '>.el-table__body-wrapper>table>tbody>tr')
          let _scrollTop = 0
          if (elements.length > 0) {
            _scrollTop = elements[that.curIndex].offsetTop
          }
          _scrollTop = _scrollTop > 330 ? _scrollTop - 300 : 0
          that.$refs.gridDataRef.setCurrentRow(that.gridData[that.curIndex]) //  选择当前行
          that.$refs.gridDataRef.bodyWrapper.scrollTop = _scrollTop //  滚到指定位置
          return false//  阻止默认行为
        } else if (e.keyCode === 27) {
          // esc 关闭
          that.closeWin()
        }
      }
    },
    unbindKeyDownEvent() {
      //  解绑事件
      document.onkeydown = null
    },
    closeWin() {
      this.visible = false
    }
  }
}
</script>
